from flask import Blueprint, render_template, request,current_app,jsonify
from flask_login import login_required, current_user
from sqlalchemy import desc

from applications.common import curd
from applications.common.curd import enable_status, disable_status
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db

from applications.models import CustomerRawYPModel,CustomerRawYPFilesModel
from pinyin import pinyin
import datetime,os
from applications.common.utils import upload as upload_curd
bp = Blueprint('raw', __name__, url_prefix='/raw')


# 用户管理
@bp.get('/yp/')
@authorize("customer:raw:main:yp")
def main():

    return render_template('customer/raw/yp/main.html')


#   用户分页查询
@bp.get('/yp/data')
@authorize("customer:raw:main:yp")
def data():
    # 获取请求参数
    客户名 = str_escape(request.args.get('客户名', type=str))

    简拼 = str_escape(request.args.get('简拼', type=str))


    filters = []
    if 客户名:
        filters.append(CustomerRawYPModel.客户名.contains(客户名))

    if 简拼:
        filters.append(CustomerRawYPModel.简拼.contains(简拼))

    query = db.session.query(
        CustomerRawYPModel
    ).filter(*filters).layui_paginate()

    return table_api(
        data=[{
            'id': item.id,
            '客户名': item.客户名,
            '简拼': item.简拼,
            '有效期至': item.有效期至,
            '审计周期': item.审计周期,
            '质保体系评估结果': item.质保体系评估结果,

            '状态': item.状态,



        } for item in query.items],
        count=query.total)

    # 用户增加


@bp.get('/yp/add')
@authorize("customer:raw:add:yp", log=False)
def add():
    return render_template('customer/raw/yp/add.html')

#   上传接口
@bp.post('/upload')
@authorize("customer:raw:add:yp", log=True)
def upload_api():
    if 'file' in request.files:
        report = request.files['file']
        mime = request.files['file'].content_type
        upload_url = current_app.config.get("UPLOADED_CUSTOMERRAWYP_DEST")

        file_url,filename = upload_curd.upload_customer_raw_yp_one(report=report, mime=mime)
        size = os.path.getsize(upload_url + '/' + filename)
        res = {
            "msg": "上传成功",
            "code": 0,
            "success": True,
            "data":
                {"src": file_url,'mime':mime,'size':size,'filename':filename}
        }
        return jsonify(res)
    return fail_api()

@bp.post('/yp/save')
@authorize("customer:raw:add:yp", log=True)
def save():
    req_json = request.get_json(force=True)
    fileds=['客户名' ,'身份信息','注册地址','状态','归属类别','备注' ,
    '联系人', '联系电话'  , '最后一次审计日期' ,  '有效期至', '审计周期',
        '仓库名称',  '仓库地址',   '仓库联系人',  '仓库联系电话',
        '仓库名称2', '仓库地址2', '仓库联系电话2', '邮箱','企业网址',
        '开户行','收款单位','账号', '质保体系评估结果']
    row={}
    for filed in fileds:
        if filed in ['客户名','身份信息','有效期至']:
            if not req_json.get(filed):
                return fail_api(msg=f"{filed}不得为空")
        if req_json.get(filed):
            row[filed]=str_escape(req_json.get(filed))

    row['简拼']=pinyin.get_initial(row['客户名'],"").upper()
    row['全拼'] =pinyin.get(row['客户名'], format='strip').upper()

    fileinfo=req_json.get("fileInfo")
    files=[]
    if fileinfo:
        for file in fileinfo:
            files.append(CustomerRawYPFilesModel(
                data_label=file['data']['filename'],
                href=file['data']['src'],
                mime=file['data']['mime'],
                size=file['data']['size'],
                enable= 1 if file['state']=='在用' else 0,
                expiration_time=file['date']
            ))
    try:

        pro=CustomerRawYPModel(**row,files=files)
        db.session.add(pro)

        db.session.commit()

    except Exception as e:
        print(e)
        return fail_api(msg=f"发生错误:{e}")
    return success_api(msg="增加成功")


# 删除用户
@bp.delete('/yp/remove/<int:id>')
@authorize("customer:raw:remove:yp", log=True)
def delete(id):
    upload_url = current_app.config.get("UPLOADED_CUSTOMERRAWYP_DEST")
    qurey = CustomerRawYPModel.query.filter_by(id=id).one()
    for file in qurey.files:
        filename = file.data_label
        file_path = os.path.join(upload_url, filename)
        try:
            os.remove(file_path)
        except Exception as e:
            print(e)
        qurey.files.remove(file)
    db.session.delete(qurey)
    try:
        db.session.commit()
    except Exception as e:
        print(e)
        return fail_api(msg=f"删除失败:{e}")


    return success_api(msg="删除成功")


#  编辑用户
@bp.get('/yp/edit/<int:id>')
@authorize("customer:raw:edit:yp", log=True)
def edit(id):
    sup_raw_info = curd.get_one_by_id(CustomerRawYPModel, id)


    return render_template('customer/raw/yp/edit.html', info=sup_raw_info)


#  编辑用户
@bp.put('/yp/update')
@authorize("customer:raw:edit:yp", log=True)
def update():
    req_json = request.get_json(force=True)
    id = str_escape(req_json.get("id"))
    # username = str_escape(req_json.get('username'))
    # real_name = str_escape(req_json.get('realName'))
    # dept_id = str_escape(req_json.get('deptId'))
    fileds = ['客户名', '身份信息', '注册地址', '状态', '归属类别', '备注',
              '联系人', '联系电话', '最后一次审计日期', '有效期至', '审计周期',
              '仓库名称', '仓库地址', '仓库联系人', '仓库联系电话',
              '仓库名称2', '仓库地址2', '仓库联系电话2', '邮箱', '企业网址',
              '开户行', '收款单位', '账号', '质保体系评估结果']
    row = {}
    for filed in fileds:
        if filed in ['客户名', '身份信息', '有效期至']:
            if not req_json.get(filed):
                return fail_api(msg=f"{filed}不得为空")
        if req_json.get(filed):
            row[filed] = str_escape(req_json.get(filed))

    row['简拼'] = pinyin.get_initial(row['客户名'], "").upper()
    row['全拼'] = pinyin.get(row['客户名'], format='strip').upper()
    row['update_at'] = datetime.datetime.now()

    fileinfo = req_json.get("fileInfo")
    files = []
    oldfiles=CustomerRawYPFilesModel.query.filter_by(Customer_raw_id=id).all()
    for oldfile in oldfiles:
        files.append(oldfile)
    if fileinfo:
        for file in fileinfo:
            files.append(CustomerRawYPFilesModel(
                data_label=file['data']['filename'],
                href=file['data']['src'],
                mime=file['data']['mime'],
                size=file['data']['size'],
                enable= 1 if '在用' in file['state'] else 0,
                expiration_time=file['date']
            ))
    row['files'] = files

    try:
        query=CustomerRawYPModel.query.filter_by(id=id).one()
        for k,v in row.items():
            setattr(query, k, v) #不能写成query[k]=v 不能写成query.k=v

        db.session.commit()
    except Exception as e :
        print(e)
        return fail_api(msg=f"更新失败,{e}")

    if not query:
        return fail_api(msg="更新失败")
    return success_api(msg="更新成功")

# 启用字典数据
@bp.put('/yp/enable')
@authorize("customer:raw:edit:yp", log=True)
def dict_data_enable():
    _id = request.get_json(force=True).get('dataId')
    if _id:
        res = curd.enable_status(model=CustomerRawYPModel, id=_id,filed='状态')
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="启动成功")
    return fail_api(msg="数据错误")


# 禁用字典数据
@bp.put('/yp/disable')
@authorize("customer:raw:edit:yp", log=True)
def dict_data_disenable():
    _id = request.get_json(force=True).get('dataId')
    if _id:
        res = curd.disable_status(model=CustomerRawYPModel, id=_id,filed='状态')
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="禁用成功")
    return fail_api(msg="数据错误")

#   用户分页查询
@bp.get('/yp/file/data')
@authorize("customer:raw:main:yp")
def file_data():
    # 获取请求参数
    id_=request.args.get('id')


    query=CustomerRawYPFilesModel.query.filter_by(Customer_raw_id=id_).all()



    return table_api(
        data=[{


            'id': item.id,
            '文件名': item.data_label,
            '大小': item.size,
            '有效期至': item.expiration_time,


            '状态': item.enable,



        } for item in query],
        count=len(query))

    # 用户增加
#  编辑字典数据
@bp.get('/yp/edit/file/')
@authorize("customer:raw:edit:yp", log=True)
def dict_data_edit():
    _id = request.args.get('dataId', type=str)
    dict_data = curd.get_one_by_id(CustomerRawYPFilesModel, _id)
    return render_template('customer/raw/yp/file/edit.html', dict_type=dict_data)
@bp.put('/yp/file/update')
@authorize("customer:raw:edit:yp", log=True)
def update_file():
    req_json = request.get_json(force=True)
    id = str_escape(req_json.get("id")) #上传文件的id

    fileds = ['expiration_time', 'description', 'enable']
    row = {}
    for filed in fileds:
        if filed in ['expiration_time', 'enable']:
            if not req_json.get(filed):
                return fail_api(msg=f"{filed}不得为空")
        if req_json.get(filed):
            row[filed] = str_escape(req_json.get(filed))



    try:
        query=CustomerRawYPFilesModel.query.filter_by(id=id).one()
        for k,v in row.items():
            setattr(query, k, v) #不能写成query[k]=v 不能写成query.k=v

        db.session.commit()
    except Exception as e :
        print(e)
        return fail_api(msg=f"更新失败,{e}")

    if not query:
        return fail_api(msg="更新失败")
    return success_api(msg="更新成功")

# 删除用户
@bp.delete('/yp/file/remove/<int:id>')
@authorize("customer:raw:edit:yp", log=True)
def file_delete(id):
    upload_url = current_app.config.get("UPLOADED_CUSTOMERRAWYP_DEST")
    qurey = CustomerRawYPFilesModel.query.filter_by(id=id).one()


    filename = qurey.data_label
    file_path = os.path.join(upload_url, filename)
    try:
        os.remove(file_path)
    except Exception as e:
        print(e)

    db.session.delete(qurey)
    try:
        db.session.commit()
    except Exception as e:
        print(e)
        return fail_api(msg=f"删除失败:{e}")


    return success_api(msg="删除成功")

# 启用字典数据
@bp.put('/yp/file/enable')
@authorize("customer:raw:edit:yp", log=True)
def file_dict_data_enable():
    _id = request.get_json(force=True).get('dataId')
    if _id:
        res = curd.enable_status(model=CustomerRawYPFilesModel, id=_id,filed='enable')
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="启动成功")
    return fail_api(msg="数据错误")


# 禁用字典数据
@bp.put('/yp/file/disable')
@authorize("customer:raw:edit:yp", log=True)
def file_dict_data_disenable():
    _id = request.get_json(force=True).get('dataId')
    if _id:
        res = curd.disable_status(model=CustomerRawYPFilesModel, id=_id,filed='enable')
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="禁用成功")
    return fail_api(msg="数据错误")